package cn.tedu.test.rpc.demo05;

import cn.tedu.test.rpc.demo03.UserServiceImpl;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo05Server {
    private static boolean isRunning=true;
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket=new ServerSocket(8000);
        while(isRunning){
            Socket socket=serverSocket.accept();
            process(socket);
            socket.close();
        }
        serverSocket.close();
    }
    private static void process(Socket socket) throws Exception{
        InputStream inputStream=socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        ObjectInputStream ois=new ObjectInputStream(inputStream);

        String clazzName=ois.readUTF();
        String methodName=ois.readUTF();
        Class[] parameterTypes=(Class[])ois.readObject();
        Object[] args=(Object[])ois.readObject();
        Class clazz=null;
        Object service=null;
        if(clazzName.equals("IUserService")) {
            clazz= UserServiceImpl.class;
            service=new UserServiceImpl();
        } else {
            clazz=ProductServiceImpl.class;
            service=new ProductServiceImpl();
        }
        Method method=service.getClass().getMethod(methodName,parameterTypes);
        Object o=method.invoke(clazz.newInstance(),args);
        ObjectOutputStream oos=new ObjectOutputStream(outputStream);
        oos.writeObject(o);
        oos.flush();
    }
}
